package com.ld.xuanKe.service.impl;

import com.ld.xuanKe.dao.UserDAO;
import com.ld.xuanKe.entity.Selectd;
import com.ld.xuanKe.entity.User;
import com.ld.xuanKe.service.SelectdService;
import com.ld.xuanKe.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
	@Resource
	private UserDAO userDAO;
	@Resource
	private SelectdService selectdService;
	public int update(User user) {
		return userDAO.update(user);
	}


	public User login(String account, String password) {
		String s = DigestUtils.md5Hex(password);
		return userDAO.findOne("from User U where U.account = ? and U.password = ?",new String[]{account,s});
	}
	public List<User> list(){
		return userDAO.find("from User U where U.status = 0",new String[]{});
	}


	public int delete(Integer id) {
		try {
			List<Selectd> selectds = selectdService.listByUserId(id);
			for (Selectd selectd : selectds) {
				selectdService.delete(selectd.getId());
			}
			userDAO.delete(User.class,id);
		} catch (Exception e) {
			return 0;
		}
		return 1;
	}



	public int register(User user) {
		//防止改变注册的用户的密码信息
		User user1 = new User();
		user1.setPassword(DigestUtils.md5Hex(user.getPassword()));
		user1.setAccount(user.getAccount());
		user1.setStatus(user.getStatus());
		user1.setUsername(user.getUsername());
		return userDAO.insert(user1);
	}


	public User getUserByAccount(String account) {
		return userDAO.findOne("from User U where U.account = ?",new String[]{account});
	}
	public User querySingle(Integer id) {
		return userDAO.findById(User.class,id);
	}

	public List<User> getUsersByLikeName(String name) {
		return userDAO.find("from User U where U.username like ?",new Object[]{"%" + name + "%"});
	}

	public int add(User user) {
		System.out.println(user);
		if(this.getUserByAccount(user.getAccount()) != null) {
			System.out.println("用户已存在");
			return 0;
		}
		user.setPassword(DigestUtils.md5Hex(user.getAccount()));
		return userDAO.insert(user);
	}
}
